package com.wtx.atguigu.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Set;

/**
 * @description: Nio 网络非阻塞编程实例
 * @author: wtx
 * @createDate: 2020/6/9
 */
public class NioServer {
    public static void main(String[] args) throws IOException {

        // 服务器的channel, 也可以注册到 Selector 上, 用于接收连接
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        Selector selector = Selector.open();

        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);

        // SelectionKey.OP_ACCEPT: 表示Selector监听的事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true){

            if (selector.select(1000) == 0){
                System.out.println("服务器等待了1s, 无连接");
                continue;
            }
            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            for (SelectionKey key : selectionKeys) {
                if (key.isAcceptable()){ //获取客户端的channel
                    try {
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        //设置为非阻塞, 否则会抛异常
                        socketChannel.configureBlocking(false);

                        // 给channel关联一个buffer, 这个buffer位于Serverchannel与channel之间
                        // 不是这个buffer: client <-> buffer <-> channel
                        socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));


                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (key.isReadable()){ // 对应的channel有消息可读

                    SocketChannel channel = (SocketChannel) key.channel();
                    // 获取channel对应的buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    try {
                        channel.read(buffer);
                        System.out.println("来自客户端: "+new String(buffer.array()));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                // 否则会抛空指针异常
                selectionKeys.remove(key);
            }
        }
    }
}
